package com.hibernate.daoimp.product;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.common.Constant;
import com.common.Page;
import com.hibernate.dao.product.ProductMessageDao;
import com.hibernate.pojo.ProductMessage;
import com.struts.form.ProductMessageForm;

public class ProductMessageDaoImp extends HibernateDaoSupport implements ProductMessageDao
{
	private Map hashmap=null;
	private boolean bool=false;
	private int record_count=0;
	
	public Map findProductMessage(final String hql,int page)
	{
		hashmap=new HashMap();
		//record_count: page start count    current page mul page display count
		record_count=page*Constant.PAGE_VIEW_COUNT;
		//get counts
		List list=this.getHibernateTemplate().find("select count(*) from ProductMessage");
		Integer counts=(Integer)list.get(0);
		//reckon page
		Page pageobject=new Page();	
		Map map=pageobject.pageCount(counts);
		//current page
		map.put("pagecur", page);
		//page object
		hashmap.put("page_content", map);
		
		list=getHibernateTemplate().executeFind(new HibernateCallback(){
		public Object doInHibernate(Session session)throws HibernateException, SQLException
		{
			Query query;
			query = session.createQuery(hql);
			//start
			query.setFirstResult(record_count);
			//end
			query.setMaxResults(Constant.PAGE_VIEW_COUNT);
			List list = query.list();
			return list;
		}
		});
		hashmap.put("productmessage_list", list);
		return hashmap;
	}
	public boolean saveProductMessage(ProductMessage message)
	{
		bool=false;
		try
		{
			this.getHibernateTemplate().save(message);
			bool=true;
		}
		catch(Exception e)
		{
			bool=false;
			e.printStackTrace();
		}
		return bool;
	}
	public boolean editProductMessage(ProductMessageForm productmessageform)
	{
		bool=false;
		return bool;
	}
	
	public boolean delProductMessage(Long id)
	{
		bool=false;
		try
		{
			ProductMessage productmessage=(ProductMessage)this.getHibernateTemplate().load(ProductMessage.class, id);
			this.getHibernateTemplate().delete(productmessage);
			bool=true;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			bool=false;
		}
		return bool;
	}
	
	public boolean deleteBatchProductMessage(String ids)
	{
		bool=false;
		return bool;
	}
	
	public List displayProductMessageInfo(Long id)
	{
		List list=this.getHibernateTemplate().find("select new map(p.product_name as product_name,pm.message as message,pm.username as username,pm.phone as phone,pm.address as address,pm.company as company) from Product p,ProductMessage pm where p.id=pm.product_id and pm.id="+id);
		return list;
	}
}
